import os,sys,subprocess,getopt
import platform
from threading import Timer
from support.const.exception import *
class Shell:
    @staticmethod
    def execute(cmd):
        retArray = []
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        while p.poll() is None:
            line = p.stdout.readline().strip()
            if(line):
                retArray.append(line.decode("utf8", 'ignore'))
        return retArray
class Opts:
    def __init__(self, shortmap, longmap):
        self.shortmap = shortmap
        self.longmap = longmap
        if('h' not in shortmap):
            self.shortmap["h"] = "Print Help Info"
        if('help' not in longmap):
            self.longmap["help"] = "Print Help Info"
    def _searchHelpInfo(self, key):
        if(key.startswith("--") and self.longmap is not None):
            key = key.lstrip("--")
            for opt in self.longmap:
                if(opt.rstrip("=") is key):
                    return self.longmap[opt]
        elif(self.shortmap is not None):
            key = key.lstrip("-")
            for opt in self.shortmap:
                if(opt.rstrip(":") is key):
                    return self.shortmap[opt]
        return "None Help Info for {}".format(key)
    def _getOptInfo(self, optmap):
        opts = []
        opts_info = ""
        if(optmap):
            for opt in optmap:
                opts.append(opt)
                if(opt.endswith(":")):
                    opts_info += "\t-{}\t\t<{}>\n".format(opt.rstrip(":"), optmap[opt])
                elif(opt.endswith("=")):
                    opts_info += "\t--{}\t\t<{}>\n".format(opt.rstrip("="), optmap[opt])
                elif(len(opt) == 1):
                    opts_info += "\t-{}\t\t{}\n".format(opt, optmap[opt])
                else:
                    opts_info += "\t--{}\t\t{}\n".format(opt, optmap[opt])
        return opts, opts_info
    
    def getHelpInfo(self):
        return self.helpinfo
        
    def getUserInput(self, retmap, needall=False):
        idelKey = list(retmap.keys())
        shortOpt, shortOptHelpInfo = self._getOptInfo(self.shortmap)
        longOpt, longOptHelpInfo = self._getOptInfo(self.longmap)
        self.helpinfo = "{}\n\n帮助信息\n{}\n{}".format(sys.argv[0],shortOptHelpInfo,longOptHelpInfo)
        try:
            opts, args = getopt.getopt(sys.argv[1:],",".join(shortOpt),longOpt)
            for opt, arg in opts:
                if opt in ('-h',"--help"):
                    print(self.helpinfo)
                    sys.exit()
                if(opt in retmap.values()):
                    key = list(retmap.keys())[list(retmap.values()).index(opt)]
                    if(len(arg) == 0):
                        arg = True
                    retmap[key] = arg
                    idelKey.remove(key)
            for key in idelKey:
                if(needall):
                    retmap[key] = input(self._searchHelpInfo(retmap[key]) + ":")
                else:
                    retmap[key] = None
        except getopt.GetoptError:
            print(self.helpinfo)
            raise OptErrException()
class Sys:
    @staticmethod
    def dump():
        return "操作系统及版本信息: {}\n\
        获取系统版本号: {}\n\
        获取系统名称: {}\n\
        系统位数: {}\n\
        计算机类型: {}\n\
        计算机名称: {}\n\
        处理器类型: {}\n\
        计算机相关信息: {}\n".format(platform.platform(),
        platform.version(),
        platform.system(),
        platform.architecture(),
        platform.machine(),
        platform.node(),
        platform.processor(),
        platform.uname())
    @staticmethod
    def getPlatform():
        system = platform.system().upper()
        bit = platform.machine().upper()
        info = ""
        if(system.startswith("WINDOWS")):
            info = "win"
        elif(system.startswith("LINUX")):
            info = "linux"
        elif(system.startswith("DARWIN")):
            info = "mac"
        else:
            info = "arm"
        if(bit == "AMD64" or bit == "I686"):
            info += "64"
        else:
            info += "32"
        return info